package com.jgssp.ad.sdk.topon.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.anythink.banner.unitgroup.api.CustomBannerAdapter;
import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;

import java.util.Map;
import java.util.UUID;

import cn.jiguang.jgssp.ad.ADJgBannerAd;
import cn.jiguang.jgssp.ad.data.ADJgAdInfo;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgBannerAdListener;

/**
 * @author songzi
 * @date 2021/12/6
 */
public class BannerAdapter extends CustomBannerAdapter {
    private ADJgBannerAd bannerAd;
    private FrameLayout flContainer;
    private String slotId;
    private boolean isAgreePrivacyStrategy;
    private boolean isBidding;
    private ATBiddingListener biddingListener;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtras) {
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoadBanner(context);
                    }

                    @Override
                    public void onFail(String s) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", s);
                        }
                    }
                });


    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }

        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoadBanner(context);
                    }

                    @Override
                    public void onFail(String msg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", msg);
                        }
                    }
                });
        return true;
    }

    private void startLoadBanner(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (!(context instanceof Activity)) {
                    if (isBidding) {
                        if (biddingListener != null) {
                            biddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.fail("context is null or context must be Activity"),
                                    null);
                        }
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1", "context is null or context must be Activity");
                        }
                    }
                    return;
                }

                flContainer = new FrameLayout(context);
                flContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                bannerAd = new ADJgBannerAd((Activity) context, flContainer);
                bannerAd.setForceCheck(false);
                bannerAd.setListener(new ADJgBannerAdListener() {
                    @Override
                    public void onAdExpose(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdShow();
                        }
                    }

                    @Override
                    public void onAdClick(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdClicked();
                        }
                    }

                    @Override
                    public void onAdClose(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdClose();
                        }
                    }

                    @Override
                    public void onAdFailed(ADJgError error) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(error.getError())
                                        , null
                                );
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError(
                                        "" + error.getCode()
                                        , "" + error.getError()
                                );
                            }
                        }
                    }

                    @Override
                    public void onAdReceive(ADJgAdInfo adInfo) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfo != null && adInfo.getECPM() > 0) {
                                    //用于标识此次竞价的唯一ID，可使用UUID或者时间戳
                                    String token = UUID.randomUUID().toString();
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.success(
                                                    adInfo.getECPM()
                                                    , token
                                                    , null
                                                    , ATAdConst.CURRENCY.RMB)
                                            , null);
                                } else {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo is null"),
                                            null);
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdCacheLoaded();
                            }
                        }
                    }
                });
                bannerAd.loadAd(slotId);
            }
        });


    }

    @Override
    public void destory() {
        if (bannerAd != null) {
            releaseLoadResource();
            bannerAd.release();
            bannerAd = null;
        }
        flContainer = null;
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    @Override
    public View getBannerView() {
        return flContainer;

    }

    /**
     * @param context
     * @param isConsent   用户是否授权
     * @param isEUTraffic 是否是欧盟地区
     * @return
     */
    @Override
    public boolean setUserDataConsent(Context context, boolean isConsent, boolean isEUTraffic) {
        isAgreePrivacyStrategy = isConsent;
        return super.setUserDataConsent(context, isConsent, isEUTraffic);
    }
}
